package com.binvshe.binvshe.mine;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.Account;
import com.binvshe.binvshe.account.AccountManager;
import com.binvshe.binvshe.account.ParamKey;
import com.binvshe.binvshe.common.QiniuFileUploader;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.mine.utils.HeadUploadUtils;
import com.binvshe.binvshe.mine.view.ChooseCityDialog;
import com.binvshe.binvshe.mine.view.ChooseSexDialog;
import com.hyphenate.easeui.model.dao.UserIconHelper;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.picture.clipimage.PhotoActionHelper;
import com.pachong.android.framework.picture.picker.release.SelectAlbumActivity;
import com.pachong.android.framework.picture.picker.utils.FileManager;
import com.pachong.android.frameworkbase.customviews.iconcontent.IconTextArrowButton;
import com.pachong.android.frameworkbase.dialog.IOSAlertListFragment;
import com.pachong.android.frameworkbase.imageloader.ImageLoader;
import com.pachong.android.frameworkbase.utils.BitmapUtil;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.SLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.Bind;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

import static android.R.attr.paddingLeft;
import static com.umeng.analytics.a.p;

public class MineInfoActivity extends BaseActivity {

    @Bind(R.id.mItbtnHead)
    IconTextArrowButton mItbtnHead;
    @Bind(R.id.mItbtnPhone)
    IconTextArrowButton mItbtnPhone;
    @Bind(R.id.mItbtnAccout)
    IconTextArrowButton mItbtnAccout;
    @Bind(R.id.mItbtnNickName)
    IconTextArrowButton mItbtnNickName;
    @Bind(R.id.mItbtnGender)
    IconTextArrowButton mItbtnGender;
    @Bind(R.id.mItbtnAddress)
    IconTextArrowButton mItbtnAddress;
    @Bind(R.id.mItbtnSign)
    TextView mItbtnSign;

    private Account mUserInfo;
    private CircleImageView mCivHead;
    private Uri mImageUri;
    private String mHeadUrl;
    private String mFilename = "/" + System.currentTimeMillis() + ".png";
    private String mFilePath = null;

    private static final int REQUEST_NICK_NAME = 626;
    private static final int REQUEST_SIGN = 816;
    public static final int TAKE_PHOTO_REQUEST = 449;
    public static final int SELECT_ALBUM_REQUEST = 540;
    public static final int REQUEST_KEY = 585;
    public static final String INTENT_SELECTED_PICTURE = "INTENT_SELECTED_PICTURE";

    enum PutMessage {
        UserHead,
        Phone,
        UserAccount,
        NickName,
        Gender,
        Province,
        City,
        Sign
    }

    public static void start(Activity activity) {
        Intent starter = new Intent(activity, MineInfoActivity.class);
        activity.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolBar();
        initView();
        onGetUserInfo();
    }

    private void initView() {
        LinearLayout.LayoutParams civheadLytParams = new LinearLayout.LayoutParams((int) getResources().getDimension(R.dimen.circleNormal), (int) getResources().getDimension(R.dimen.circleNormal));
        mCivHead = new CircleImageView(this);
        mItbtnHead.addSubView(mCivHead, civheadLytParams, Gravity.RIGHT | Gravity.CENTER_VERTICAL);

        mFilePath = FileManager.getImagePath(this);

    }

    private void initToolBar() {
        getCustomToolbar().setTitle("个人信息");
        enableBackButton();
    }

    private void onGetUserInfo() {
        setUserInfo(AccountManager.getCurrentAccount());
    }

    private void setUserInfo(Account acc) {
        this.mUserInfo = acc;
        refreshUserInfo();
    }

    private void refreshUserInfo() {
        if (mUserInfo == null) {
            return;
        } else {

            mItbtnPhone.setSubText(mUserInfo.getPhone());
            mItbtnAccout.setSubText(mUserInfo.getUserId() + "");
            mItbtnNickName.setSubText(mUserInfo.getNickName());
            int sex = mUserInfo.getGender();
            mItbtnGender.setSubText((String.valueOf(sex) != null) ? (sex == 1 ? "男" : "女") : "");
            if (mUserInfo.getProvince() != null && mUserInfo.getCity() != null) {
                mItbtnAddress.setSubText(mUserInfo.getProvince() + " " + mUserInfo.getCity());
            } else {
                mItbtnAddress.setSubText("");
            }
            mItbtnSign.setText(mUserInfo.getSign());
            try {
                ImageLoader.with(this)
                        .load(mUserInfo.getPortrait())
                        .into(mCivHead)
                        .start();
            } catch (NullPointerException e) {
                Log.d("zzz", "use default icon");
            }
        }
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.act_mine_info, null);
    }

    @OnClick({R.id.mItbtnHead, R.id.mItbtnNickName, R.id.mItbtnGender, R.id.mItbtnAddress, R.id.mLintbtnSign})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mItbtnHead:
                showIOSAlertFrag();
                break;
            case R.id.mItbtnNickName:
                EditInfoActivity.start(this, mUserInfo.getNickName(), REQUEST_NICK_NAME);
                break;
            case R.id.mItbtnGender:
                ChooseSexDialog chooseSexDialog = new ChooseSexDialog();
                chooseSexDialog.show(getSupportFragmentManager(), "tag");
                chooseSexDialog.setmOnClickable(new ChooseSexDialog.SexClickable() {
                    @Override
                    public void btnEnter(int sex) {
                        mUserInfo.setGender(sex);
                        onPutUserInfo(PutMessage.Gender);
                    }
                });
                break;
            case R.id.mItbtnAddress:
                ChooseCityDialog chooseCityDialog = new ChooseCityDialog();
                chooseCityDialog.show(getSupportFragmentManager(), "tag");
                chooseCityDialog.setOnClickable(new ChooseCityDialog.ProvinceClickable() {
                    @Override
                    public void btnEnter(String province, String city) {
                        mItbtnAddress.setSubText(province + " " + city);
                        mUserInfo.setProvince(province);
                        onPutUserInfo(PutMessage.Province);
                        mUserInfo.setCity(city);
                        onPutUserInfo(PutMessage.City);
                    }
                });
                break;
            case R.id.mLintbtnSign:
                SignActivity.start(this, mUserInfo.getSign(), REQUEST_SIGN);
                break;
        }
    }

    private void showIOSAlertFrag() {
        final IOSAlertListFragment diaFrag = new IOSAlertListFragment();
        String[] strArr = new String[]{"拍照", "从照片库选择"};
        diaFrag.setActionList(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    //拍照
                    case 0:
                        Intent intent_TP = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        mImageUri = createNewPictureUri(MineInfoActivity.this);
                        intent_TP.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
                        startActivityForResult(intent_TP, TAKE_PHOTO_REQUEST);
                        break;
                    //相册
                    case 1:
                        Intent intentPickPhoto = new Intent(MineInfoActivity.this, SelectAlbumActivity.class);
                        intentPickPhoto.putExtra(SelectAlbumActivity.RELEASE_IMGS_NUM, 0);
                        intentPickPhoto.putExtra(SelectAlbumActivity.INTENT_MAX_NUM, 1);
                        startActivityForResult(intentPickPhoto, SELECT_ALBUM_REQUEST);
                        break;
                }
                diaFrag.dismiss();
            }
        }, strArr).show(getSupportFragmentManager());
    }

    private Uri createNewPictureUri(Context context) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile = new File(FileManager.getImagePath(context) + File.separator + "IMG_" + timeStamp + ".jpg");
        return Uri.fromFile(mediaFile);
    }

    private void onPutUserInfo(PutMessage message) {
        IHttpRequest request = new MyHttpRequest(this);
        JSONObject jobj = new JSONObject();
        try {
            switch (message) {
                case UserHead:
                    jobj.put(ParamKey.PORTRAIT, mUserInfo.getPortrait());
                    break;
                case Phone:
                    jobj.put(ParamKey.PHONE, mUserInfo.getPhone());
                    break;
                case UserAccount:
                    jobj.put(ParamKey.USER_ID, mUserInfo.getUserId());
                    break;
                case NickName:
                    jobj.put(ParamKey.NICK_NAME, mUserInfo.getNickName());
                    break;
                case Gender:
                    jobj.put(ParamKey.GENDER, mUserInfo.getGender());
                    break;
                case Province:
                    jobj.put(ParamKey.PROVINCE, mUserInfo.getProvince());
                    break;
                case City:
                    jobj.put(ParamKey.CITY, mUserInfo.getCity());
                    break;
                case Sign:
                    jobj.put(ParamKey.SIGN, mUserInfo.getSign());
                    break;
            }
            request.put(UrlCenter.USER_UPDATA, jobj, new DataRequestListener<Object>(Object.class) {
                @Override
                public void onSuccess(Object reg) {
                    setUserInfo(mUserInfo);
                }

                @Override
                public void onStart(Context context, String url) {
                    enableProgress(false);
                    super.onStart(context, url);
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    Toast.makeText(MineInfoActivity.this, strMsg, Toast.LENGTH_SHORT).show();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void clipImage(String url, String outputUrl) {
        int maxWidth = 0;
        int windowWidth = this.getWindow().getWindowManager().getDefaultDisplay().getWidth();
        if (windowWidth <= 480) {
            maxWidth=100;
        }
        PhotoActionHelper.clipImage(this)
                .input(url)
                .output(outputUrl)
                .maxOutputWidth(maxWidth)
                .requestCode(REQUEST_KEY)
                .start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        String changetext = null;
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_NICK_NAME || requestCode == REQUEST_SIGN) {
                changetext = data.getExtras().getString(EditInfoActivity.RESULT_STRING);
                switch (requestCode) {
                    case REQUEST_NICK_NAME:
                        mItbtnNickName.setSubText(changetext);
                        mUserInfo.setNickName(changetext);
                        onPutUserInfo(PutMessage.NickName);
                        // IM更新用户信息
                        UserIconHelper.setUserIcon(MineInfoActivity.this, mUserInfo.getPhone(), mUserInfo.getNickName(), mUserInfo.getPortrait());
                        break;
                    case REQUEST_SIGN:
                        mItbtnSign.setText(changetext);
                        mUserInfo.setSign(changetext);
                        onPutUserInfo(PutMessage.Sign);
                        break;
                }
            } else if (requestCode == TAKE_PHOTO_REQUEST) {
                clipImage(mImageUri.getPath().toString(), mFilePath + mFilename);
            } else if (requestCode == SELECT_ALBUM_REQUEST) {
                mHeadUrl = data.getExtras().getStringArrayList(INTENT_SELECTED_PICTURE).get(0);
                clipImage(mHeadUrl, mFilePath + mFilename);
            } else if (requestCode == REQUEST_KEY) {
                //图片压缩上传 (80*80)
                setBitmapSize();
                sendRequest();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void sendRequest() {
        /**
         *  七牛云上传头像。 目前仍然使用自己服务器保存
         */

        String filePath = mFilePath + mFilename;
        SLog.e("vivi", "filePath " + filePath);

        QiniuFileUploader.uploadFile(this, filePath, new com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener<String>(String.class) {
            @Override
            public void onSuccess(String url) {
                super.onSuccess(url);
                mUserInfo.setPortrait(url);
                onPutUserInfo(PutMessage.UserHead);
                EasyToast.showToast(MineInfoActivity.this, "修改成功");
                UserIconHelper.setUserIcon(MineInfoActivity.this, mUserInfo.getPhone(), mUserInfo.getNickName(), mUserInfo.getPortrait());
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
        HeadUploadUtils.uploadHead(this, mFilePath + mFilename, new HeadUploadUtils.HeadUploadable() {
            @Override
            public void onSuccess(String url) {
                mUserInfo.setPortrait(url);
                onPutUserInfo(PutMessage.UserHead);
                EasyToast.showToast(MineInfoActivity.this, "修改成功");
                UserIconHelper.setUserIcon(MineInfoActivity.this, mUserInfo.getPhone(), mUserInfo.getNickName(), mUserInfo.getPortrait());
            }

            @Override
            public void onFailureUpload(Throwable t, int errorNo, String strMsg) {
            }
        });
    }

    private void setBitmapSize() {
        Bitmap userHeader = BitmapUtil.decodeBitmapFromFilePath(mFilePath + mFilename, 80, 80);
        BitmapUtil.saveBitmap(userHeader, mFilePath + mFilename, true);
    }
}
